let express = require('express')
// token
const jwt = require('jsonwebtoken')

let app = express()

// 连接数据库
require('./db/init')
// 同步数据模型（数据库创建）
// require('./db/model/User')
// require('./db/model/shoplist')
// 导入主路由登录注册
const main = require('./router/main')
// 主页列表增删改查
const home = require('./router/home')

//设置跨域访问
app.all("*",function(req,res,next){
    res.header('Access-Control-Allow-Origin', '*')
    res.header('Access-Control-Allow-Headers', 'X-Requested-With, mytoken')
    res.header('Access-Control-Allow-Headers', 'X-Requested-With, Authorization')
    res.setHeader('Content-Type', 'application/json;charset=utf-8')
    res.header('Access-Control-Allow-Headers', 'Content-Type,Content-Length, Authorization, Accept,X-Requested-With')
    res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS')
    if (req.method == 'OPTIONS') res.send(200)
    /*让options请求快速返回*/ else next()
})


// 隐藏请求头部分
app.disable("x-powered-by")
app.disable("etag")



// 拦截/user请求
app.use('/', async (req, res, next) => {
    // console.log(req.host);
    if (req.url == '/user/login' || req.url == '/user/register') {
        next()
        return
    } else {
        console.log("进入其他接口");
        // console.log("app", req.headers);
        const token = String(req.headers.authorization)
        const uphone = jwt.verify(token, 'nodestudy')
        if (!uphone) {
            var fail = {
                message: "无token或token无效",
                code: 6000
            }
            res.send(fail)
            return
        } else {
            next()
        }
    }

})

// 获取post请求体数据
app.use(express.urlencoded({
    extended: false
}))

// 登录注册
app.use('/user', main)

app.use('/home', home)


app.listen(3000, (err) => {
    if (err) {
        console.log(err);
    } else {
        console.log("服务启动成功");
    }
})